package com.bstek.bdf2.protal.home;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.Date;
import java.util.Map;

import com.bstek.bdf2.core.context.ContextHolder;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.StringType;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.bstek.bdf2.core.CoreHibernateDao;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.dorado.data.provider.Page;
import com.bstek.utils.AppUtils;


/**
 *  操作首页的dao
 * @author zxq
 */
@Repository(HomeManagelDao.BEAN_ID)
public class HomeManagelDao extends CoreHibernateDao {
	public static final String BEAN_ID="mes.HomeManagelDao";

	/**
	 *  分页查询首页配置信息
	 * @param page
	 * @param parameter
	 */
	public void queryHomeManagel(Page<HomeManagel> page, Map<String, Object> parameter) {
		DetachedCriteria dc = DetachedCriteria.forClass(HomeManagel.class);
		if(parameter!=null) {
			String issueState = (String) parameter.getOrDefault("issueState", null);
			if(!StringUtils.isEmpty(issueState)) {
				dc.add(Restrictions.eq("issueState", issueState));
			}
			String moduleProtal = (String) parameter.getOrDefault("moduleProtal", null);
			if(!StringUtils.isEmpty(moduleProtal)) {
				dc.add(Restrictions.eq("moduleProtal", moduleProtal));
			}
			 Date beginDate = (Date) parameter.getOrDefault("beginDate", null);
			 Date endDate = (Date) parameter.getOrDefault("endDate", null);
 
//			 if(beginDate!=null&&endDate!=null) {
//				 dc.add(Restrictions.sqlRestriction("{alias}.create_time between ? and ?",
//						 new Object[] {
//								 getLocalDateStr(beginDate, "yyyy-MM-dd"),
//								 getLocalDateStr(endDate, "yyyy-MM-dd")},
//				 StringType.INSTANCE));
//			 }
			 if(beginDate!=null) {
				 dc.add(Restrictions.sqlRestriction("{alias}.create_time>=?",getLocalDateStr(beginDate, "yyyy-MM-dd"),StringType.INSTANCE));
 			 }
			 if(endDate!=null) {
 				 dc.add(Restrictions.sqlRestriction("{alias}.create_time<=?",getLocalDateStr(endDate, "yyyy-MM-dd"),StringType.INSTANCE));
 			 }
		}
		 dc.addOrder(Order.desc("createTime"));
		this.pagingQuery(page, dc);
	}

	public static void main(String[] args) {
		String str = getLocalDateStr(new Date(), "yyyy-MM-dd");
		System.err.println(str);
	}
	
	/**
	 *  Date转String
	 * @param date
	 * @param formatter
	 * @return
	 */
	public static String getLocalDateStr(Date date,String formatter) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatter);
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);     
        String dateStr = dateTimeFormatter.format(localDateTime);     
	     return dateStr;
	 }

	/**
	 * 保存更新首页信息
	 * @param coll
	 */
	public void saveHomeManagel(Collection<HomeManagel> coll) {
		Session session=this.getSession();
		for(HomeManagel emp:coll){
			
			EntityState state=EntityUtils.getState(emp);
			String roleId = emp.getRoleId();
			Assert.notNull(roleId, "部门的编号不能为空！");
 			if(state.equals(EntityState.NEW)){
				String uuid = AppUtils.generateUUID();
				emp.setId(uuid);
				emp.setCreateTime(new Date());
				emp.setCreateUser(ContextHolder.getLoginUserName());
				saveRoleProtal(emp.getRoleId(),uuid,session);
				session.save(emp);
			}else if(state.equals(EntityState.MODIFIED)){
				System.out.println(emp.getId());
				updateRoleProtal(roleId, emp.getId(),session);
				session.update(emp);
			}else if(state.equals(EntityState.DELETED)){
				deleteRoleProtal(roleId, emp.getId(),session);
				session.delete(emp);
				
			}else{
				
			}
		}
		
	}
	
	
	/** 更新RoleProtal中间表
	 * @param roleId
	 * @param protalId
	 * @param session
	 */
	public void updateRoleProtal(String roleId,String protalId,Session session) {
		deleteRoleProtal(roleId, protalId,session);
		saveRoleProtal(roleId, protalId,session);
	}
	
	public void deleteRoleProtal(String roleId, String protalId,Session session) {

//		Session session = this.getSessionFactory().openSession();
//		try {
//		
//		} finally {
//			session.flush();
//			session.close();
//		}
		
		session.createQuery("delete " + MesRoleProtal.class.getName() + " u where u.protalId = :protalId")
		.setString("protalId", protalId).executeUpdate();
	}
 
	
	
	public void  saveRoleProtal(String roleId,String protalId,Session session){
 		String[] split = roleId.split(",");
		for (int i = 0; i < split.length; i++) {
 			MesRoleProtal mesRoleProtal = new MesRoleProtal();
			mesRoleProtal.setId(AppUtils.generateUUID());
			mesRoleProtal.setRoleId(split[i]);
			mesRoleProtal.setProtalId(protalId);
			mesRoleProtal.setCreateTime(new Date());
			mesRoleProtal.setCreateUser(ContextHolder.getLoginUserName());
			session.save(mesRoleProtal);
		}
	

	}
 
 	
 	
}
